package com.algo.rpc.server;

import com.algo.rpc.common.ClassUtils;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * serviceConfig 扫描类
 */
public class ServiceConfigScanner {

    private static final Logger logger = Logger.getLogger(ServiceConfigScanner.class);

    private static final Class SERVICE_PROVIDER_ANNOTION_CLASS_NAME = ServiceProvider.class;

    private String packageName;

    public ServiceConfigScanner(String packageName) {
        this.packageName = packageName;
    }

    public List<ServiceConfig> doScan() {
        List<Class> classes = ClassUtils.getAllClassByAnnotationFromPkg(packageName, SERVICE_PROVIDER_ANNOTION_CLASS_NAME);
        if (classes == null || classes.size() == 0) {
            return Collections.emptyList();
        }

        List<ServiceConfig> serviceConfigs = new ArrayList<ServiceConfig>(classes.size());

        for (Class claszz : classes) {
            ServiceProvider serviceProvider = (ServiceProvider) claszz.getAnnotation(SERVICE_PROVIDER_ANNOTION_CLASS_NAME);
            if (claszz.isAssignableFrom(serviceProvider.serviceInteface())) {
                logger.error("ServiceProvider parse error, claszz is not assign from " + serviceProvider.serviceInteface());
            }

            ServiceConfig serviceConfig = new ServiceConfig();
            serviceConfig.setServiceInterface(serviceProvider.serviceInteface());
            serviceConfig.setServiceImpl(claszz);
            serviceConfigs.add(serviceConfig);
        }
        return serviceConfigs;
    }

}
